using AutoMapper;
using BackData;
using Domain.DTOs.ProcessSteps;
using Domain.工艺工序;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Makesteps;

namespace Team.API.Applocation.Hanldler.Makesteps
{
    /// <summary>
    /// 获取工艺流程树形结构处理器
    /// 根据产品名称和版本查询工艺流程树形结构
    /// </summary>
    public class GetMakestepTreeHandler : IRequestHandler<GetMakestepTreeCommand, APIResult<List<MakestepTreeDTO>>>
    {
        private readonly IRepository<Makestepmodel> repository;
        private readonly IMapper mapper;
        private readonly ILogger<GetMakestepTreeHandler> logger;

        public GetMakestepTreeHandler(IRepository<Makestepmodel> repository, IMapper mapper, ILogger<GetMakestepTreeHandler> logger)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 获取工艺流程树形结构
        /// 根据产品名称和版本查询，Parentid=0的为根节点，递归查询子节点
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>工艺流程树形结构列表</returns>
        public async Task<APIResult<List<MakestepTreeDTO>>> Handle(GetMakestepTreeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证必填参数：产品名称和版本必须提供
                if (string.IsNullOrWhiteSpace(request.Goodsname))
                {
                    return APIResult<List<MakestepTreeDTO>>.Faile("产品名称不能为空");
                }

                if (string.IsNullOrWhiteSpace(request.Version))
                {
                    return APIResult<List<MakestepTreeDTO>>.Faile("版本号不能为空");
                }

                // 查询根节点（Parentid=0），匹配产品名称和版本
                var rootNodes = await repository.GetAll()
                    .Where(x => !x.IsDel 
                        && x.Parentid == 0 
                        && x.Goodsname == request.Goodsname 
                        && x.Version == request.Version)
                    .OrderBy(x => x.Processcode)
                    .ToListAsync();

                if (rootNodes == null || rootNodes.Count == 0)
                {
                    logger.LogInformation("未找到产品名称={Goodsname}，版本={Version}的工艺流程数据", request.Goodsname, request.Version);
                    return APIResult<List<MakestepTreeDTO>>.Ok("未找到数据", new List<MakestepTreeDTO>());
                }

                // 将实体转换为DTO，并递归获取子节点
                var result = new List<MakestepTreeDTO>();
                foreach (var rootNode in rootNodes)
                {
                    var dto = mapper.Map<MakestepTreeDTO>(rootNode);
                    dto.Children = await GetChildrenAsync(rootNode.Id, request.Goodsname, request.Version);
                    result.Add(dto);
                }

                logger.LogInformation("成功获取产品名称={Goodsname}，版本={Version}的工艺流程树形结构，共{Count}个根节点", 
                    request.Goodsname, request.Version, result.Count);

                return APIResult<List<MakestepTreeDTO>>.Ok("获取成功", result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取工艺流程树形结构失败，产品名称={Goodsname}，版本={Version}", 
                    request.Goodsname, request.Version);
                return APIResult<List<MakestepTreeDTO>>.Faile($"获取工艺流程树形结构失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 递归获取子节点
        /// 根据父级ID查询子节点，同时需要匹配产品名称和版本（子节点可能没有产品名称，则只匹配版本）
        /// </summary>
        /// <param name="parentId">父级ID</param>
        /// <param name="goodsname">产品名称（用于过滤）</param>
        /// <param name="version">版本号（用于过滤）</param>
        /// <returns>子节点列表</returns>
        private async Task<List<MakestepTreeDTO>> GetChildrenAsync(long parentId, string goodsname, string version)
        {
            // 查询子节点：Parentid等于指定的父级ID，匹配版本，未删除
            var children = await repository.GetAll()
                .Where(x => !x.IsDel 
                    && x.Parentid == parentId 
                    && x.Version == version)
                .OrderBy(x => x.Processcode)
                .ToListAsync();

            if (children == null || children.Count == 0)
            {
                return new List<MakestepTreeDTO>();
            }

            // 转换为DTO，并递归获取每个子节点的子节点
            var result = new List<MakestepTreeDTO>();
            foreach (var child in children)
            {
                var dto = mapper.Map<MakestepTreeDTO>(child);
                dto.Children = await GetChildrenAsync(child.Id, goodsname, version);
                result.Add(dto);
            }

            return result;
        }
    }
}

